package com.lagou.edu.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;

public class MD5Utils {
    private static Logger log = LoggerFactory.getLogger(MD5Utils.class);
    private static final String SIGN_TYPE = "MD5";
    private static final String CHARSET_NAME = "UTF-8";

    /**
     * MD5加盐加密
     *
     * @param str  加密前数据
     * @param salt 盐值
     * @return String 加密后的数据
     */
    public static String encrypt(String str, String salt) {
        try {
            MessageDigest md5 = MessageDigest.getInstance(SIGN_TYPE);
            md5.update((str + salt).getBytes(CHARSET_NAME));
            return byte2hex(md5.digest());
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("md5 加密异常", e);
            }
        }
        return "";
    }

    /**
     * 功能描述：转16进制
     *
     * @param bytes 字节数组
     * @return String 转为16进账
     * @author cakin
     * @date 2020/8/20
     */
    public static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }

    public static void main(String[] args) {
        String encrypt = encrypt("2731468048@qq.com", "1234");
        System.out.println(encrypt);
        System.out.println("DB2310D76EEAC3FB1469BC7EEDB61D48".equals(encrypt));
        System.out.println(encrypt.length());
    }

}
